package com.itheima.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Sound;
import com.itheima.domain.vo.ErrorResult;
import com.itheima.domain.vo.SoundVo;
import com.itheima.dubbo.api.FriendApi;
import com.itheima.dubbo.api.SoundApi;
import com.itheima.dubbo.api.UserInfoApi;
import com.itheima.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.Collections;
import java.util.List;

/**
 * @author 阿鹏
 * @date 2021/2/25 1:21
 */
@Service
@Slf4j
public class PeachBlossomService {

    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer webServer;
    @Reference
    private SoundApi soundApi;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Reference
    private FriendApi friendApi;
    @Reference
    private UserInfoApi userInfoApi;

    /**
     * 发送语音
     * @param soundFile
     * @return
     */
    public ResponseEntity sendSoundFile(MultipartFile soundFile) throws IOException {

        Long userId = UserHolder.getUserId();

        /// 判断有没有
        Boolean boo = redisTemplate.hasKey("user_sound_save_" + userId);
        //为空说明今天没发过
        if (!boo) {
            redisTemplate.opsForValue().set("user_sound_save_" + userId, "0", Duration.ofDays(1));
        }

        //查看今天发了几条
        String numbers = redisTemplate.opsForValue().get("user_sound_save_" + userId);
        if(Integer.parseInt(numbers)<10){

            //保存到fastdfs中
            String suffix = soundFile.getOriginalFilename().substring(soundFile.getOriginalFilename().lastIndexOf(".") + 1);
            StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(),soundFile.getSize(),suffix,null);

            String soundPathUrl = webServer.getWebServerUrl() + storePath.getFullPath();
            Sound sound = new Sound();
            sound.setUserId(userId);
            sound.setSoundUrl(soundPathUrl);

            //保存到MongoDB
            soundApi.save(sound);
            //每次发完后,设置value值自增加一
            redisTemplate.opsForValue().increment("user_sound_save_" + userId);
        }


        return ResponseEntity.ok(null);
    }

    /**
     * 接收语音
     * @return
     */
    public ResponseEntity receiveSoundFile() throws Exception {

        //获取当前用户ID
        Long userId = UserHolder.getUserId();

        /// 判断有没有接收过
        Boolean boo = redisTemplate.hasKey("user_sound_receive_" + userId);
        //为空说明今天没接收过
        if (!boo) {
            redisTemplate.opsForValue().set("user_sound_receive_" + userId, "0", Duration.ofDays(1));
        }

        //调用api查询所有
        List<Sound> soundList = soundApi.findSoundList();
        //判断集合是否为空
        if (!CollectionUtils.isEmpty(soundList)) {
            //打乱顺序
            Collections.shuffle(soundList);

            //获取当前用户获取了几条呢
            String num = redisTemplate.opsForValue().get("user_sound_receive_" + userId);
            for (Sound sound : soundList) {
                //判断是否是当前用户和朋友发的语音,排除这两项
                if (sound.getUserId().longValue() != userId && !friendApi.isFriend(userId, sound.getUserId())) {

                    if (Integer.parseInt(num) < 10) {
                        //封装vo
                        SoundVo vo = new SoundVo();
                        BeanUtils.copyProperties(sound,vo);
                        vo.setId(sound.getUserId().intValue());
                        UserInfo userInfo = userInfoApi.findById(sound.getUserId());
                        BeanUtils.copyProperties(userInfo,vo);
                        //先自增加一
                        redisTemplate.opsForValue().increment("user_sound_receive_"+userId);
                        //设置剩余次数字段时,要除去本次,获取最新值
                        vo.setRemainingTimes(10-Integer.parseInt(redisTemplate.opsForValue().get("user_sound_receive_" + userId)));
                        //接收语音后,删除该语音
                        soundApi.delete(sound.getId());
                        //返回vo
                        return ResponseEntity.ok(vo);
                    }
                }
            }
        }
        return ResponseEntity.ok(null);
    }


    /**
     * 设置定时任务,更新每日发送/接收次数
     */
    @Scheduled(cron = "0 0 0 1/1 * ? ")
    public void  update(){

        //查询所有的语音文件
        List<Sound> soundList = soundApi.findSoundList();
        //判断集合是否为空
        if (!CollectionUtils.isEmpty(soundList)) {
            //遍历集合拿到每个数据
            for (Sound sound : soundList) {
                //获取发送语音的用户id
                Long userId = sound.getUserId();
                //根据用户id更新用户的发送和接收次数
                redisTemplate.opsForValue().set("user_sound_save_"+userId,"0", Duration.ofDays(1));
                redisTemplate.opsForValue().set("user_sound_receive_"+userId,"0",Duration.ofDays(1));
            }
        }

    }
}
